<template>
  <div class="accident-info">
    <p class="accident-title">
      事故详情
      <span class="close-accident" @click="hideInfo">X</span>
    </p>
    <div class="accident-video">
      <VideoPlayer style="height:100%" :options="getVideoOptions" />
    </div>
    <p class="accident-title">事故处理</p>
    <!-- 算法图片 -->
    <div v-if="accidentSource ===1" class="accident-pic">
      <img :src="accidentPic">
    </div>
    <!-- 事故信息 -->
    <div v-if="!onCall && accidentSource ===1" class="accident-detail">
      <p v-for="(item,index) in list" :key="index">
        {{ item.label }}<span>{{ obj[item.key] }}</span>
      </p>
    </div>
    <!-- 事故记录 -->
    <div v-if="onRecord" class="accident-record">
      <n-input
        v-model:value="accidentRecod"
        type="textarea"
        placeholder="请输入内容"
        maxlength="140"
      />
    </div>
    <!-- 调动无人机 -->
    <div v-if="onCall" class="drone-call">
      <p>调动无人机</p>
      <n-select v-model:value="selectedAirId" placeholder="请选择机场" :options="airOptions" />
      <n-select v-model:value="selectedDSPId" placeholder="算法实例" :options="dspOptions" />
    </div>
    <!-- 操作按钮 -->
    <div class="operate-btns">
      <n-button v-if="waitProcess" class="confirm" @click="currentUAVGo">前往</n-button>
      <!-- 正在执行日常巡检的无人机才能执行继续巡检 -->
      <n-button v-if="waitProcess && accidentSource ===1 && inspectionStatus === 10" class="cancel" @click="otherUAVGo">继续巡检</n-button>

      <n-button v-if="inProcess" class="confirm" @click="recordAccident">记录</n-button>
      <n-popconfirm
        v-if="inProcess"
        @positive-click="completeTask()"
        @negative-click="handleNegativeClick"
      >
        <template #trigger>
          <n-button class="cancel">处理完成</n-button>
        </template>
        是否确认事故处理完成?
      </n-popconfirm>

      <n-button v-if="onCall" class="confirm" @click="fly2Point">前往</n-button>
      <n-button v-if="onCall" class="cancel" @click="cancelOtherGo">返回</n-button>

      <n-button v-if="onRecord" class="confirm" @click="submitRecord">提交</n-button>
      <n-button v-if="onRecord" class="cancel" @click="cancelSubmit">返回</n-button>

      <n-button v-if="afterProcess" class="confirm" @click="endTask">返航</n-button>
      <n-button v-if="afterProcess && droneForwardType ===1 && inspectionStatus === 10" class="cancel" @click="continueTask">继续巡检</n-button>
    </div>
  </div>
</template>
<script>
import { ref, reactive, toRefs, watch, computed, useAttrs, inject } from 'vue'
import VideoPlayer from '@/components/VideoPlayer/index.vue'
// api
import { accidentForward, accidentRecord, accidentHandle, droneBack, taskContinue, dspServiceList, accidentComplete } from '@/api/accident/index.js'
import { getAirList } from '@/api/task/index.js'
export default {
  components: { VideoPlayer },
  props: {
    info: {
      type: Object,
      default: () => {}
    },
    accidentVideo: {
      type: String,
      default: ''
    }
  },
  emits: ['hide', 'remove'],
  setup(props, { emit }) {
    const data = reactive({
      accidentInfo: null,
      accidentPic: null,
      accidentId: null,
      list: [
        { label: '事故类型', key: 'questionName' },
        { label: '事故航道', key: 'legName' },
        { label: '负责部门', key: 'deptName' },
        { label: '巡检时间', key: 'formatTime' }
      ],
      obj: {
        questionName: '船只',
        legName: '大运河',
        deptName: '拓恒软件部',
        createTime: '2023-04-10 12:00:00'
      },
      waitProcess: true, // 未处理
      inProcess: false, // 处理中
      onRecord: false, // 记录中
      onCall: false, // 调度中
      afterProcess: false, // 已处理
      accidentRecod: null,
      param: {
        accidentId: null,
        droneForwardType: null,
        airportId: null,
        airportName: null,
        droneId: null,
        dspServiceInstId: null
      },
      dspOptions: [],
      selectedDSPId: null,
      airOptions: [],
      selectedAirId: null,
      accidentStatus: 1, // 事故状态 1:未处理; 2:处理中; 3:已忽略; 4已处理; 5:已完成;
      accidentSource: 1, // 来源：1:巡检任务产生; 2:应急任务产生; 3:手动添加
      droneForwardType: 1, // 无人机前往类型：1：原无人机直接前往；2：新无人机前往；3：手动添加的应急事故，无人机前往；
      inspectionStatus: 15 // 巡检任务状态 5任务待飞行 7飞行失败 10任务飞行中 15任务飞行完成
    })
    watch(() => props.info, (value) => {
      // if (JSON.stringify(value) !== '{}') {
      if (value !== null) {
        data.accidentInfo = value
        data.accidentSource = value?.source
        data.accidentPic = value?.fileImage
        data.accidentId = value?.id
        data.accidentStatus = value?.status
        data.inspectionStatus = value?.inspectionStatus
        data.droneForwardType = value?.droneForwardType || 1
        if (data.accidentStatus === 1) { // 未处理
          data.waitProcess = true
          data.onCall = false
          data.inProcess = false
          data.onRecord = false
          data.afterProcess = false
        } else if (data.accidentStatus === 2) { // 处理中
          data.waitProcess = false
          data.onCall = false
          data.inProcess = true
          data.onRecord = false
          data.afterProcess = false
        } else if (data.accidentStatus === 4) { // 已处理
          data.waitProcess = false
          data.onCall = false
          data.inProcess = false
          data.onRecord = false
          data.afterProcess = true
        }
        data.obj = {
          ...data.accidentInfo
        }
        getDspList()
      }
    })

    /**
     *  初始化获取算法实例一次即可,通常不会大变
     */
    const getDspList = async() => {
      data.dspOptions = []
      const res = await dspServiceList()
      if (res.code === 0) {
        if (res.data?.length) {
          for (let i = 0; i < res.data.length; i++) {
            data.dspOptions.push({
              label: res.data[i]?.name,
              value: res.data[i]?.dspServiceInstId
            })
          }
        }
      }
    }

    /**
     *  获取在线且空闲无人机列表,常变
     */
    const airList = async() => {
      data.airOptions = []
      const res = await getAirList()
      if (res.code === 0) {
        if (res.data?.records?.length) {
          res.data?.records.map(item => {
            // 在线且空闲
            if (item?.online & item?.status === 1) {
              data.airOptions.push({
                label: item?.name,
                value: item?.id,
                droneId: item?.droneId
              })
            }
          })
        }
      }
    }

    // 当前巡检无人机前往
    const currentUAVGo = async() => {
      // 日常巡检结束了，就派新无人机前往
      if (data.inspectionStatus === 15) {
        // 其他无人机前往
        otherUAVGo()
      } else {
        data.param.accidentId = data.accidentId
        data.param.droneForwardType = data.droneForwardType
        const res = await accidentForward(data.param)
        if (res.code === 0) {
        // 未处理变为处理中
          data.waitProcess = false
          data.inProcess = true
        }
      }
    }

    // 其他无人机前往
    const otherUAVGo = () => {
      airList()
      data.waitProcess = false
      // 调度中
      data.onCall = true
    }

    // 指点飞行
    const fly2Point = async() => {
      // 调度中变为处理中
      if (data.selectedAirId !== null && data.selectedDSPId !== 0) {
        for (let i = 0; i < data.airOptions?.length; i++) {
          if (data.selectedAirId === data.airOptions[i]?.value) {
            data.param = {
              accidentId: data.accidentId,
              droneForwardType: 2,
              airportId: data.selectedAirId,
              airportName: data.airOptions[i]?.label,
              droneId: data.airOptions[i]?.droneId,
              dspServiceInstId: data.selectedDSPId
            }
          }
        }
        const res = await accidentForward(data.param)
        if (res.code === 0) {
          // 其他无人机不应该有继续巡检按钮
          data.droneForwardType = 2
          // 变为处理中
          data.onCall = false
          data.inProcess = true
        }
      } else {
        $message.error('请先选择无人机场和算法实例!')
      }
      return false
    }

    // 取消指点飞行
    const cancelOtherGo = () => {
      data.selectedAirId = null
      data.selectedDSPId = null
      Object.keys(data.param).forEach((key) => (data.param[key] = null))
      // 状态变为调度中
      data.waitProcess = true
      data.onCall = false
    }

    // 事故记录
    const recordAccident = () => {
      data.inProcess = false
      data.onRecord = true
    }

    // 提交事故记录
    const submitRecord = async() => {
      if (data.accidentRecod !== null) {
        const res = await accidentRecord({
          accidentId: data.accidentId,
          remark: data.accidentRecod
        })
        if (res.code === 0) {
          data.inProcess = true
          data.onRecord = false
          data.accidentRecod = null
        }
      }

      return false
    }
    // 取消提交事故记录
    const cancelSubmit = () => {
      data.inProcess = true
      data.onRecord = false
      data.accidentRecod = null
      return false
    }

    // 处理完成
    const completeTask = async() => {
      // 若是手动创建的事故,处理完成就直接改变事故状态为已完成
      if (data.droneForwardType === 3) {
        const res = await accidentComplete(data.accidentId)
        if (res.code === 0) {
          data.inProcess = false
          emit('remove')
        }
      } else {
        const res = await accidentHandle({
          accidentId: data.accidentId
        })
        if (res.code === 0) {
          data.inProcess = false
          data.afterProcess = true
        }
      }
    }

    // 结束任务,无人机返航
    const endTask = async() => {
      const res = await droneBack({ accidentId: data.accidentId })
      if (res.code === 0) {
        emit('remove')
      }
    }

    // 继续巡检任务
    const continueTask = async() => {
      const res = await taskContinue({ accidentId: data.accidentId })
      if (res.code === 0) {
        emit('remove')
      }
    }

    const getVideoOptions = computed(() => {
      return {
        videoUrl: props.accidentVideo || null,
        videoTitle: null,
        live: true
      }
    })

    const hideInfo = () => {
      emit('hide')
    }

    return {
      ...toRefs(data),
      getVideoOptions,
      currentUAVGo,
      otherUAVGo,
      fly2Point,
      cancelOtherGo,
      recordAccident,
      submitRecord,
      cancelSubmit,
      completeTask,
      handleNegativeClick() {},
      endTask,
      continueTask,
      hideInfo
    }
  }
}
</script>
<style lang="scss" scoped>
.accident-info {
    // position: absolute;
    // left: 10px;
    // top: 100px;
    width: 345px;
    // height: 659px;
    background: #222222;
    .accident-title {
      width: 100%;
      height: 35px;
      font-size: 16px;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 35px;
      padding-left: 13px;
        .close-accident {
            width: 30px;
            height: 30px;
            text-align: center;
            line-height: 30px;
            font-size: 16px;
            float: right;
            color: #fff;
            cursor: pointer;
        }
    }
    .accident-pic {
      width: 345px;
      height: 177px;
      border-radius: 0px 0px 0px 0px;
      img {
        width: 100%;
        height: 100%;
      }
    }

    .accident-detail {
        height: 120px;
        margin-top: 13px;
        p {
            height: 30px;
            line-height: 30px;
            font-size: 16px;
            color: #fff;
            padding-left: 16px;
            span {
              margin: 0 16px;
            }
        }
    }

    .drone-call {
      width: 310px;
      padding-left: 17px;
      p {
        color: #fff;
        font-size: 16px;
        height: 30px;
        line-height: 30px;
      }
      ::v-deep(.n-select){
        margin: 3px 0;
      }
    }
    .accident-record {
      margin: 10px 0;
    }

    .operate-btns {
      width: 200px;
      height: 43px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin: 13px 0;
      .confirm {
        background-color:#0E42D2;
        color:#fff;
      }

      .cancel {
        background-color: #C9CDD4;
        color: #4E5969;
      }
    }

}

</style>
